package com.bw.config.captcha;

import com.alibaba.fastjson.JSON;

import com.bw.common.Result;
import com.bw.common.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class SecurityCaptchaFilter extends OncePerRequestFilter {

    @Autowired
    StringRedisTemplate redisTemplate;

    private static String defaultFilterProcessUrl = "/sys/login";

    private static String method = "POST";
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (method.equalsIgnoreCase(request.getMethod()) && defaultFilterProcessUrl.equals(request.getServletPath())){
            String captcha = request.getParameter("picCode");
            String uuid = request.getParameter("uuid");
            if (!StringUtils.hasLength(captcha)){
                //设置客户端的响应内容类型
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                //获取输出流
                ServletOutputStream outputStream = response.getOutputStream();
                String message = "验证码不能为空";
                int code = ResultCode.ERROR;
                //将错误信息转换成JSON
                String result = JSON.toJSONString(Result.fail().code(code).message(message));
                outputStream.write(result.getBytes(StandardCharsets.UTF_8));
                outputStream.flush();
                outputStream.close();
            }
            Object o = redisTemplate.opsForValue().get("captcha:" + uuid);
            if (!captcha.equals(o)){
                //设置客户端的响应内容类型
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                //获取输出流
                ServletOutputStream outputStream = response.getOutputStream();
                String message = "图片验证码错误";
                int code = ResultCode.ERROR;
                //将错误信息转换成JSON
                String result = JSON.toJSONString(Result.fail().code(code).message(message));
                outputStream.write(result.getBytes(StandardCharsets.UTF_8));
                outputStream.flush();
                outputStream.close();
            }
            redisTemplate.delete("captcha:" + uuid);
        }
        filterChain.doFilter(request,response);
    }
}
